package com.smartleanx.module.hrm.framework.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.smartleanx.module.hrm.dal.dataobject.salary.vo.EmployeeExcel;
import com.smartleanx.module.hrm.framework.excelUtil.HiddenColumn;
import com.smartleanx.module.hrm.framework.excelUtil.handler.CustomCellDropDownHandler;
import lombok.Data;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Data
public class SpinnerWriteHandler implements SheetWriteHandler {
    //传入下拉框数据
    private  Map<Integer, String[]> mapDropDown;

    /**
     * 超过 LIMIT 的大小就使用 sheet关联下拉，否则直接设置下拉
     */
    public static final Integer LIMIT = 20;

    public SpinnerWriteHandler() {
    }

    public SpinnerWriteHandler(Map<Integer, String[]> mapDropDown) {
        this.mapDropDown = mapDropDown;
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        //设置下拉框数据
        Sheet sheet = writeSheetHolder.getSheet();
        sheet.setDefaultRowHeight((short) 400);
        // 开始设置下拉框
        DataValidationHelper helper = sheet.getDataValidationHelper();
        for (Map.Entry<Integer, String[]> entry : mapDropDown.entrySet()) {
            //起始行、终止行、起始列、终止列
            CellRangeAddressList addressList = new CellRangeAddressList(1, 3000, entry.getKey(), entry.getKey());
            //设置下拉框数据
            DataValidationConstraint constraint;
            if (entry.getValue().length < LIMIT) {
                // 直接设置下拉
                constraint = helper.createExplicitListConstraint(entry.getValue());
            } else {
                // sheet关联下拉
                constraint = helper.createFormulaListConstraint(entry.getKey() + "!$A$1:$A$" + entry.getValue().length);
            }

            DataValidation dataValidation = helper.createValidation(constraint, addressList);
            //处理Excel兼容性问题
            if (dataValidation instanceof XSSFDataValidation){
                dataValidation.setSuppressDropDownArrow(true);
                dataValidation.setShowErrorBox(true);
            } else {
                dataValidation.setSuppressDropDownArrow(false);
            }
            sheet.addValidationData(dataValidation);
        }

    }
}

